﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Com.CMS263.Util;
using Com.CMS263.PO;

namespace Com.CMS263.BLL
{
    /// <summary>
    /// 解析文章列表标签 cms:list
    /// </summary>
    public class ArtListTransform : ITag
    {

        /// <summary>
        /// 要解析的含有标签的html代码
        /// </summary>
        private string ctx = null;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="ctx">页面内容</param>
        /// 
        List<string> tags = new List<string>();
        List<string> pages = new List<string>();

        TagUtil tu = new TagUtil();

        ArtBaseBLL bll = new ArtBaseBLL();
        ExtValueBLL evbll = new ExtValueBLL();
        //public ArtListTransform(string ctx)
        //{
        //    this.ctx = ctx;
        //}

        public int count = 0;

        public int pagesize = 10;
        /// <summary>
        /// 得到替换标签后的内容
        /// </summary>
        /// <returns>返回替换后的结果</returns>
        public string Replace(string ctx)
        {

            //得到所有标签
            tags = tu.GetTag(ctx, "cms:list", tags);
            if (tags.Count == 0)
            {
                return ctx;
            }
            int i = 0;
            foreach (string tag in tags)
            {
                int page = 0;
                pages = tu.GetTag(tag, "cms:pages", pages);

                // string tagpages = pages[i];
                string innnerListHTML = tu.GetInnerHTML("cms:list", tag);
                /// <summary>
                /// 文章分类编号
                /// </summary>
                int menuID = 0;
                /// <summary>
                /// 每页文章条数，默认为10条
                /// </summary>
                int pageSize = 10;

                //得到包含属性的标签字符串
                int end = tag.IndexOf(">");
                string arrtStr = tag.Substring(1, end - 1);

                //解析标签得到所有的属性

                Dictionary<string, string> attrDic = tu.Getattribute(arrtStr);
                List<string> menuidlist = new List<string>();
                string strmenuid = "";
                if (!string.IsNullOrEmpty(attrDic["menuid"]))
                {
                    if (attrDic["menuid"].ToLower() != "\"request\"")
                    {
                        strmenuid = attrDic["menuid"].Replace("\"", "");
                        menuidlist = strmenuid.Split(',').ToList<string>();
                        // menuID = int.Parse(str);
                    }
                    else
                    {
                        //如果是通过传递过来的参数取分类的那么就用参数得到编号
                        string para = System.Web.HttpContext.Current.Request[attrDic["paraname"].Replace("\"", "")];
                        if (!string.IsNullOrEmpty(para))
                        {
                            strmenuid = para;
                            menuidlist = strmenuid.Split(',').ToList<string>();
                        }
                        else
                        {
                            throw new Exception("分类参数名称错误，请使用正确的参数名称传递参数");
                        }
                    }

                }

                if (!string.IsNullOrEmpty(attrDic["pagesize"]))
                {
                    pageSize = int.Parse(attrDic["pagesize"].Replace("\"", ""));
                }
                //获取分页标签
                List<string> requestlist = new List<string>();
                requestlist = tu.GetTag(innnerListHTML, "cms:pages", requestlist);

                //获取属性拆成键值对
                string requestname = "";
                if (requestlist.Count != 0)
                {
                    Dictionary<string, string> pagedic = tu.Getattribute(requestlist[0]);
                    requestname = pagedic["pagename"].Replace("\"", "");

                    //根据上面的到的编号和页码数取得所要的数据
                    page = Convert.ToInt32(System.Web.HttpContext.Current.Request[requestname]);
                }
                IList<ArtBase> ablist = new List<ArtBase>();
                if (page == 0)
                {
                    page = 1;
                }
                string state = attrDic["state"].Replace("\"", "");
                string keyname = attrDic["keyname"].Replace("\"", "");
                string keyvalue = System.Web.HttpContext.Current.Request[keyname];

                ablist = bll.GetListBySortIds(strmenuid, state, "", page, pageSize);




                string alllist = "";
                foreach (ArtBase a in ablist)
                {
                    a.valueList = evbll.GetExtValueByArtId(a.id);
                }
                //解析列表标签，循环替换出列表
                List<string> links = new List<string>();
                links = tu.GetTag(tag, "cms:links", links);


                //循环连接连接标签
                foreach (string str in links)
                {

                    //解析里面的<cms:attribute  field=""  length=""/>标签并用一条数据中的各个属性替换标签
                    List<string> attrs = new List<string>();
                    attrs = tu.GetTag(str, "cms:attribute", attrs);

                    //循环分析连接中的属性标签
                    string allLink = "";

                    //循环累加的连接字符串


                    foreach (ArtBase ab in ablist)
                    {
                        string innerHTML = tu.GetInnerHTML("cms:links", str);
                        foreach (string attr in attrs)
                        {

                            Dictionary<string, string> attrlist = tu.Getattribute(attr);
                            string attrvalue = "";
                            int filedID = 0;
                            string field = attrlist["field"].Replace("\"", "").ToLower();
                            int length = 0;
                            if (field.ToLower() == "title")
                            {
                                attrvalue = ab.title.ToString();
                            }
                            else if (field.ToLower() == "adddate")
                            {
                                string v = "";
                                attrvalue = ab.addDate.ToString();

                                if (attrlist.TryGetValue("formate", out v))
                                {
                                    v = attrlist["formate"].Replace("\"", "");
                                    attrvalue = ab.addDate.ToString(v);
                                }
                            }
                            else if (field.ToLower() == "menuid")
                            {
                                attrvalue = ab.menuId.ToString();
                            }
                            else if (field.ToLower() == "id")
                            {
                                attrvalue = ab.id.ToString();
                            }

                            else
                            {
                                //当是属性编号时，将属性编号变成整形，否则报错
                                try
                                {
                                    filedID = int.Parse(field);
                                    var obj = from values in ab.valueList where values.attrId == filedID select values;
                                    if (obj != null)
                                    {
                                        attrvalue = obj.First().val;
                                    }
                                    else
                                    {
                                        throw new Exception("属性值错误，没有编号为" + field + "的扩展属性");
                                    }
                                }
                                catch
                                {
                                    throw new Exception("属性值错误，请检查属性值：" + field);
                                }
                            }

                            //如果有长度要求，那么进行截取
                            if (!string.IsNullOrEmpty(attrlist["length"]))
                            {
                                string l = attrlist["length"].Replace("\"", "");
                                if (!string.IsNullOrEmpty(l))
                                {
                                    length = Convert.ToInt32(l);
                                    attrvalue = StringUtil.GetHtml(attrvalue, length);
                                }
                            }

                            //将link标签中所有属性数据替换掉

                            innerHTML = innerHTML.Replace(attr, attrvalue);


                        }

                        allLink += innerHTML;

                    }

                    //文章循环完毕，替换调<cms:links>标记
                    innnerListHTML = innnerListHTML.Replace(str, allLink);

                }

                if (pages.Count > 0)
                {
                    //分页
                    int count = 0;

                    count = bll.GetListBySortIds(strmenuid, "");

                    string pagestr = "";
                    pagestr = EnPager.GetNumPager(5, count, pageSize, page, keyvalue, requestname);



                    //  string pagestr = EnPager.GetNumPager(5, count, pageSize, page, attrDic["keyname"].Replace("\"", "").ToString(), requestname);
                    //分页数据替换分页代码
                    if (pages.Count > 0)
                    {
                        innnerListHTML = innnerListHTML.Replace(pages[0], pagestr);
                    }

                    alllist += innnerListHTML;
                    ctx = ctx.Replace(tag, alllist);
                }
                else
                {
                    ctx = ctx.Replace(tag, innnerListHTML);
                }
                i++;

            }

            return ctx;
        }




    }
}
